<!-- 启动评估后回答问题页 -->
<template>
  <div class="risk-assessment-management-start">
    <card class="card" :isCustomHeader="true" :isCustomFooter="true">
      <template #header>
        <t-breadcrumb maxItemWidth="150">
          <t-breadcrumbItem @click="$router.replace('/risk-assessment/management')">评估管理</t-breadcrumbItem>
          <t-breadcrumbItem>问卷填写</t-breadcrumbItem>
          <t-breadcrumbItem>{{ qsInformation.name }}</t-breadcrumbItem>
        </t-breadcrumb>
      </template>
      <t-row class="start-filling">
        <t-col :span="3">
          <answer-tree
            v-model="activeNodeName"
            :status="status"
            :questionObject="questionObject"
            :treeOptions="treeOptions"
            :answer="qsInformation.answer"
            :riskObject="qsInformation.qsRsTemplateList ?? {}"
            @onTreeSelect="onChangePageNo"
          />
        </t-col>
        <t-col :span="9">
          <survey-content
            v-show="activeNodeName.length > 0"
            ref="survey"
            v-model="qsInformation.answer"
            :isReviewor="isReviewor"
            :questionnaireStatus="status"
            :questionObject="questionObject"
            :riskObject="qsInformation.qsRsTemplateList ?? {}"
            @handleActions="handleActions"
            @visibleChanged="onVisibleChanged"
          />
          <div v-show="activeNodeName.length === 0" class="empty-question">暂无数据</div>
        </t-col>
      </t-row>
      <template #footer>
        <t-row justify="end">
          <t-space>
            <t-button theme="default" @click="$router.replace('/risk-assessment/management')">返回</t-button>
            <t-button
              v-show="
                (status === QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED && isReviewor) ||
                status === QUESTIONNAIRE_STATUS.TO_BE_FILLED
              "
              @click="handleOnSave"
            >
              保存
            </t-button>
            <t-button
              v-show="
                (status === QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED && isReviewor) ||
                (status === QUESTIONNAIRE_STATUS.TO_BE_FILLED && isInitiator)
              "
              @click="handleOnSubmit"
            >
              提交
            </t-button>
          </t-space>
        </t-row>
      </template>
    </card>
    <t-dialog
      ref="dialog"
      width="600px"
      top="48px"
      :visible.sync="dialogVisible"
      :closeOnOverlayClick="false"
      :header="dialogTitle[actionType]"
      :footer="
        actionType === ANSWER_ACTIONS.EDIT ||
        actionType === ANSWER_ACTIONS.ASSIGNED ||
        actionType === ANSWER_ACTIONS.MESSAGE
      "
      @confirm="handleOnDialogConfirm"
      @closed="handleOnDialogClose"
    >
      <t-form v-if="dialogVisible" ref="form" class="risk-form" :data="formData" :rules="FORM_RULES" label-align="top">
        <template v-if="actionType === ANSWER_ACTIONS.EDIT">
          <t-space direction="vertical" style="width: 100%">
            <template v-if="['radiogroup', 'checkbox', 'boolean'].includes(questionObject[questionName].type)">
              <t-form-item :label="questionObject[questionName].title" name="value">
                <t-checkbox-group
                  v-if="questionObject[questionName].type === 'checkbox'"
                  v-model="formData.value"
                  :options="questionObject[questionName].allChoices"
                  @change="handleCheckboxChange"
                />
                <t-radio-group
                  v-if="questionObject[questionName].type === 'radiogroup'"
                  v-model="formData.value"
                  :options="questionObject[questionName].allChoices"
                />
                <t-radio-group
                  v-if="questionObject[questionName].type === 'boolean'"
                  v-model="formData.value"
                  :options="questionObject[questionName].allChoices"
                />
                <t-input
                  v-if="
                    (questionObject[questionName].type === 'radiogroup' && formData.value === 'other') ||
                    (questionObject[questionName].type === 'checkbox' && formData.value.includes('other'))
                  "
                  v-model="formData.valueComment"
                  style="margin-top: 16px"
                />
              </t-form-item>
            </template>
            <div class="risk-discovery">
              <span class="title">评审结果：</span>
              <div class="risk-box">
                <div
                  class="risk-box__item"
                  :class="{ red: ![RISK_STATUS.NO, RISK_STATUS.TO_BE_CONFIRMED].includes(formData.level) }"
                  @click="formData.level = RISK_STATUS.LOW"
                >
                  发现风险
                </div>
                <div
                  class="risk-box__item"
                  :class="{ green: formData.level === RISK_STATUS.NO }"
                  @click="formData.level = RISK_STATUS.NO"
                >
                  未发现风险
                </div>
                <div
                  class="risk-box__item"
                  :class="{ blue: formData.level === RISK_STATUS.TO_BE_CONFIRMED }"
                  @click="formData.level = RISK_STATUS.TO_BE_CONFIRMED"
                >
                  不确定
                </div>
              </div>
            </div>
            <template v-if="formData.level && ![RISK_STATUS.NO, RISK_STATUS.TO_BE_CONFIRMED].includes(formData.level)">
              <t-form-item label="风险等级" name="level">
                <t-radio-group class="level" v-model="formData.level" variant="primary-filled">
                  <t-radio-button
                    v-for="(item, key) in filterRiskOptions"
                    :key="key"
                    :value="Number(key)"
                    :style="{ background: formData.level === Number(key) ? item.backgroundColor : '#c5c5c5' }"
                  >
                    {{ item.label }}
                  </t-radio-button>
                </t-radio-group>
              </t-form-item>
              <t-row :gutter="16">
                <t-col :span="6">
                  <t-form-item label="风险类型" name="type">
                    <t-select
                      v-model="formData.type"
                      creatable
                      filterable
                      multiple
                      placeholder="请选择风险类型"
                      :options="typeOptions"
                    />
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item label="标签" name="label">
                    <t-select
                      v-model="formData.label"
                      creatable
                      filterable
                      multiple
                      placeholder="请选择风险标签"
                      :options="labelOptions"
                    />
                  </t-form-item>
                </t-col>
              </t-row>
              <t-form-item label="风险描述" name="description">
                <t-textarea v-model="formData.description" placeholder="请输入风险描述" autosize />
              </t-form-item>
              <t-form-item label="法律依据" name="law">
                <t-textarea v-model="formData.law" placeholder="请输入内容" autosize />
              </t-form-item>
              <t-form-item label="标准依据" name="standard">
                <t-textarea v-model="formData.standard" placeholder="请输入内容" autosize />
              </t-form-item>
              <t-form-item label="合规参考案例" name="compliance">
                <t-textarea v-model="formData.compliance" placeholder="请输入内容" autosize />
              </t-form-item>
              <t-form-item label="添加附件" name="file">
                <upload v-model="files" />
              </t-form-item>
            </template>
          </t-space>
        </template>
        <template v-if="actionType === ANSWER_ACTIONS.ASSIGNED">
          <t-form-item label="填写人" name="content">
            <t-select
              v-model="formData.content"
              placeholder="请选择填写人"
              :popupProps="{ 'z-index': 9999 }"
              :options="userArr"
            /> </t-form-item
        ></template>
        <template v-if="actionType === ANSWER_ACTIONS.UPLOAD">
          <upload
            v-model="files"
            :disabled="!isEditAllData"
            @oneFileSuccess="oneFileSuccess"
            @oneFileRemove="oneFileRemove"
          />
        </template>
        <template v-if="actionType === ANSWER_ACTIONS.MESSAGE">
          <t-list :split="true">
            <t-list-item v-for="item in messageArr" :key="item.id">
              <template #content>
                <t-comment
                  :avatar="item.sysUserAvatar ?? 'https://tdesign.gtimg.com/site/avatar.jpg'"
                  :author="item.sysUserName"
                  :datetime="item.time"
                  :content="item.content"
                />
              </template>
            </t-list-item>
          </t-list>
          <t-form-item label="留言" name="content" v-show="isEditAllData">
            <t-input v-model="formData.content" placeholder="请输入留言" />
          </t-form-item>
        </template>
        <template v-if="actionType === ANSWER_ACTIONS.HISTORY">
          <t-list :split="true">
            <t-list-item v-for="item in historyArr" :key="item.id">
              <template #content>
                <t-comment
                  :avatar="item.sysUserAvatar ?? 'https://tdesign.gtimg.com/site/avatar.jpg'"
                  :author="item.sysUserName"
                  :datetime="item.time"
                  :content="item.content"
                />
              </template>
            </t-list-item>
          </t-list>
        </template>
      </t-form>
    </t-dialog>
  </div>
</template>

<script>
import Card from '@/components/Card/index.vue';
import AnswerTree from './components/AnswerTree.vue';
import SurveyContent from '@/components/SurveyContent/index.vue';
import Upload from '@/components/Upload/index.vue';

import { mapGetters } from 'vuex';
import {
  requestQsList,
  requestAddQsDetail,
  requestQsDetail,
  requestDeleteQsDetail,
  requestSaveQsList,
  // requestCommitQsList,
} from '@/service/risk-assessment/management';
import { requestUserByOrg } from '@/service/business-management/role';
import {
  generateTreeArray,
  generateSurveyJsonAddReadonly,
  generateHistoryArray,
  generateFilterSurveyJson,
  validateQuestion,
  validateRiskLevel,
} from './utils/common';
import { ANSWER_ACTIONS, QUESTIONNAIRE_STATUS } from '@/constants/risk-assessment-management';
import {
  riskOptions,
  filterRiskOptions,
  typeOptions,
  labelOptions,
  RISK_STATUS,
} from '@/constants/risk-assessment-template';
import { FILE_URL_PREFIX } from '@/constants/index';

// 表单校验规则
const FORM_RULES = {
  value: [{ required: true, message: '请选择答案', type: 'error' }],
  content: [{ required: true, message: '请输入内容', type: 'error' }],
  level: [{ required: true, message: '请选择风险等级', type: 'error' }],
  description: [{ required: true, message: '请输入风险描述', type: 'error' }],
  // openLevel: [{ required: true, message: '请选择模板权限', type: 'error' }],
  // welcomeMessage: [{ required: true, message: '请输入欢迎语', type: 'error' }],
};
// dialog标题
const dialogTitle = {
  [ANSWER_ACTIONS.EDIT]: '编辑信息',
  [ANSWER_ACTIONS.FLAG]: '标记',
  [ANSWER_ACTIONS.ASSIGNED]: '指派',
  [ANSWER_ACTIONS.UPLOAD]: '上传文件',
  [ANSWER_ACTIONS.MESSAGE]: '留言信息',
  [ANSWER_ACTIONS.HISTORY]: '历史答题记录',
};

export default {
  name: 'riskAssessmentManagementAnswer',
  components: { SurveyContent, Card, Upload, AnswerTree },
  data() {
    return {
      // 表单校验规则
      FORM_RULES,
      // 操作类型
      ANSWER_ACTIONS,
      // 风险状态
      RISK_STATUS,
      // 问卷状态
      QUESTIONNAIRE_STATUS,
      // 风险选项
      riskOptions,
      filterRiskOptions,

      // 树结构数据
      treeOptions: [],
      // 活跃的树节点名数组
      activeNodeName: [],
      // 问卷数据
      qsInformation: {},
      // 问题对象
      questionObject: {},
      // survey问题对象
      surveyJson: {},

      // dialog标题
      dialogTitle,
      // dialog是否显示
      dialogVisible: false,
      // 指派人员列表
      userArr: [],
      // 留言信息数组
      messageArr: [],
      // 历时答题记录数组
      historyArr: [],
      // 文件列表
      files: [],
      // 表单数据
      formData: {
        level: RISK_STATUS.NO,
      },
      // 风险类型列表
      typeOptions,
      // 风险标签列表
      labelOptions,

      // 当前问卷id
      qsQuestionId: undefined,
      // 当前操作类型
      actionType: undefined,
      // 当前问题name
      questionName: undefined,
      // 当前问题id
      questionId: undefined,
    };
  },
  computed: {
    ...mapGetters('user', ['cId']),
    // 当前问卷状态
    status() {
      return this.qsInformation.status;
    },
    // 当前登录用户是不是这张问卷的发起人
    isInitiator() {
      return this.cId === this.qsInformation.initiatedId;
    },
    // 当前登录用户是不是这张问卷的审核人
    isReviewor() {
      return this.cId === this.qsInformation.reviewId;
    },
    // 判断当前登录用户是否有编辑权限
    isEditAllData() {
      if (this.status === QUESTIONNAIRE_STATUS.TO_BE_FILLED) {
        if (!this.questionName) return false;
        const question = this.$refs.survey.getQuestionByName(this.questionName);
        if (question.readOnly) return false;
      }
      if (this.status === QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED && !this.isReviewor) return false;
      if (this.status === QUESTIONNAIRE_STATUS.COMPLETED) return false;
      return true;
    },
  },
  watch: {
    // 根据树的活跃节点变化显示问卷问题
    activeNodeName(newVal) {
      if (Object.keys(this.surveyJson).length === 0) return;
      this.$refs.survey.init(generateFilterSurveyJson(this.surveyJson, newVal), true);
    },
  },
  mounted() {
    const { id } = this.$route.query;
    if (!id) return;
    // 根据问卷id获取问卷
    this.qsQuestionId = Number(id);
    this.fetchData();
  },
  methods: {
    async fetchData() {
      const res = await requestQsList(this.qsQuestionId);
      if (!res || res.isError) return;

      // 根据流转数组来处理问卷问题是否只读，添加收藏数据，初始化问题对象
      const { newJson, newObject } = generateSurveyJsonAddReadonly(res, res.qsListDetailList);
      this.qsInformation = res;
      this.questionObject = newObject;
      // 左侧树结构
      this.treeOptions = generateTreeArray(res.question?.pages);
      this.surveyJson = newJson;
      this.$refs.survey.changeAnswerData(res.answer);
    },
    // 点击操作盒子的操作
    async handleActions(type, name, questionEl, questionId) {
      this.actionType = type;
      this.questionName = name;
      this.questionId = questionId;
      if (type === ANSWER_ACTIONS.EDIT) {
        const riskData = this.qsInformation.qsRsTemplateList[name];
        const newFormData = riskData ? JSON.parse(JSON.stringify(riskData)) : {};
        if (newFormData.file) {
          this.files = newFormData.file
            .split(',')
            .filter((i) => i)
            .map((path) => {
              const name = path.split('/').pop();
              const size = name?.match(/\d+\./g).pop();
              return {
                name,
                status: 'success',
                url: FILE_URL_PREFIX + path,
                size,
                path,
              };
            })
            .filter((i) => i);
        }
        newFormData.questionName = name;
        newFormData.level = newFormData.level ?? RISK_STATUS.NO;
        newFormData.type = newFormData.type ? JSON.parse(newFormData.type) : [];
        newFormData.label = newFormData.label ? JSON.parse(newFormData.label) : [];
        if (this.qsInformation.answer[name] !== undefined) {
          newFormData.value = JSON.parse(JSON.stringify(this.qsInformation.answer[name]));
        }
        if (this.qsInformation.answer[`${name}-Comment`]) {
          newFormData.valueComment = this.qsInformation.answer[`${name}-Comment`];
        }
        this.formData = newFormData;

        if (['radiogroup', 'checkbox'].includes(this.questionObject[name].type)) {
          const question = this.$refs.survey.getQuestionByName(name);
          const allChoices = [...this.questionObject[name].choices];
          if (question.hasSelectAll) allChoices.push({ value: 'all', label: question.selectAllText });
          if (question.hasNone) allChoices.push({ value: 'none', label: question.noneText });
          if (question.hasOther) allChoices.push({ value: 'other', label: question.otherText });
          this.questionObject[this.questionName].allChoices = allChoices;
          if (this.questionObject[name].type === 'checkbox') {
            this.formData.value = this.formData.value ?? [];
            this.handleCheckboxChange(this.formData.value, 'isCheckAll');
          }
        }

        if (this.questionObject[name].type === 'boolean') {
          const question = this.$refs.survey.getQuestionByName(name);
          const allChoices = [
            { value: question.valueFalse ?? false, label: question.labelFalse },
            { value: question.valueTrue ?? true, label: question.labelTrue },
          ];
          this.questionObject[this.questionName].allChoices = allChoices;
        }
      }
      if (type === ANSWER_ACTIONS.FLAG) {
        if (!this.isEditAllData) {
          this.$message.warning('无操作权限');
          return;
        }
        const res = await requestAddQsDetail({
          content: this.questionObject[name].isFlag ? '0' : undefined,
          qsQuestionId: this.qsQuestionId,
          questionName: name,
          type,
        });
        if (!res || res.isError) return;
        this.$set(this.questionObject[name], 'isFlag', !this.questionObject[name].isFlag);
        // this.questionObject[name].isFlag = !this.questionObject[name].isFlag;
        if (this.questionObject[name].isFlag) {
          questionEl.querySelector('.box__item-1').src = './images/survey-button-1-full.svg';
          this.$message.success('标记成功');
        } else {
          questionEl.querySelector('.box__item-1').src = './images/survey-button-1.svg';
          this.$message.info('已取消标记');
        }
        return;
      }
      if (type === ANSWER_ACTIONS.ASSIGNED && this.userArr.length === 0) {
        if (!this.isEditAllData) {
          this.$message.warning('无操作权限');
          return;
        }
        const res = await requestUserByOrg();
        if (!res || res.isError) return;
        this.userArr = res.filter((i) => i.id !== this.cId).map((i) => ({ label: i.name, value: i.id }));
      }
      if (type === ANSWER_ACTIONS.UPLOAD) {
        const arr = await requestQsDetail({
          type: ANSWER_ACTIONS.UPLOAD,
          qsQuestionId: this.qsQuestionId,
          questionName: name,
        });
        const files_arr = arr
          ?.map(({ id, content }) => {
            if (!content) return;
            const name = content.split('/').pop();
            const size = name?.match(/\d+\./g).pop();
            return {
              id,
              name,
              status: 'success',
              url: FILE_URL_PREFIX + content,
              size,
              path: content,
            };
          })
          .filter((i) => i);
        this.files = files_arr;
      }
      if (type === ANSWER_ACTIONS.MESSAGE) {
        const arr = await requestQsDetail({
          type: ANSWER_ACTIONS.MESSAGE,
          qsQuestionId: this.qsQuestionId,
          questionName: name,
        });
        if (arr.length === 0 && !this.isEditAllData) {
          this.$message.warning('暂无留言记录');
          return;
        }
        this.messageArr = arr;
      }
      if (type === ANSWER_ACTIONS.HISTORY) {
        const arr = await requestQsDetail({
          type: ANSWER_ACTIONS.HISTORY,
          qsQuestionId: this.qsQuestionId,
          questionName: name,
        });
        if (arr.length === 0) {
          this.$message.warning('暂无答题记录');
          return;
        }
        this.historyArr = generateHistoryArray(this.questionObject[name], arr);
      }
      this.dialogVisible = true;
    },
    // 操作盒子dialog确定后的操作
    handleOnDialogConfirm() {
      this.$refs.form.validate().then(async (res) => {
        if (res === true) {
          if (this.actionType === ANSWER_ACTIONS.EDIT) {
            if (this.formData.value) {
              if (this.formData.value instanceof Array) {
                const index = this.formData.value.indexOf('all');
                if (index > -1) {
                  this.formData.value.splice(index, 1);
                }
              }
              this.qsInformation.answer[this.questionName] = this.formData.value;
              this.$refs.survey.setValue(this.questionName, this.formData.value);
            }
            if (this.formData.valueComment) {
              this.qsInformation.answer[`${this.questionName}-Comment`] = this.formData.valueComment;
              this.$refs.survey.setComment(this.questionName, this.formData.valueComment);
            }
            this.formData.file = this.files
              .filter((i) => i.status === 'success')
              .map((i) => i.path)
              .join(',');
            this.formData.label = JSON.stringify(this.formData.label);
            this.formData.type = JSON.stringify(this.formData.type);
            this.formData.description = this.formData.description ?? '';
            this.$set(this.qsInformation.qsRsTemplateList, this.questionName, this.formData);
            this.$refs.survey.renderRiskInfo(this.questionName, this.questionId);
          }
          if (this.actionType === ANSWER_ACTIONS.ASSIGNED) {
            const res = await requestAddQsDetail({
              content: `${this.formData.content}`,
              qsQuestionId: this.qsQuestionId,
              questionName: this.questionName,
              type: this.actionType,
            });
            if (!res || res.isError) return;
            const user = this.userArr.find((i) => this.formData.content === i.value);
            this.questionName.split(',').forEach((name) => {
              if (this.questionObject[name]) {
                if (!this.isInitiator) this.$set(this.questionObject[name], 'readOnly', true);
                this.$set(this.questionObject[name], 'assignedName', user.label);
              }
              // this.qsInformation.answer[name] = undefined;
              // this.$refs.survey.setValue(name, undefined);
            });
            this.$refs.survey.init(generateFilterSurveyJson(this.surveyJson, this.activeNodeName), true);
            this.$message.success('指派成功');
          }
          if (this.actionType === ANSWER_ACTIONS.MESSAGE) {
            const res = await requestAddQsDetail({
              content: `${this.formData.content}`,
              qsQuestionId: this.qsQuestionId,
              questionName: this.questionName,
              type: this.actionType,
            });
            if (!res || res.isError) return;
            this.$set(
              this.questionObject[this.questionName],
              'messageNum',
              this.questionObject[this.questionName].messageNum + 1,
            );
            this.$message.success('留言成功');

            const textEl = document.querySelector(`.survey #${this.questionId} .text-${ANSWER_ACTIONS.MESSAGE}`);
            textEl.innerHTML = this.questionObject[this.questionName].messageNum;
          }
          this.dialogVisible = false;
        }
      });
    },
    // 保存问卷的操作
    async handleOnSave() {
      if (!this.qsQuestionId) return;

      Object.entries(this.questionObject).forEach(([key]) => {
        if (this.qsInformation.answer[key] instanceof Array) this.qsInformation.answer[key].sort();
      });
      const res = await requestSaveQsList(this.qsInformation);
      if (!res || res.isError) return;
      await this.fetchData();
      this.$refs.survey.init(generateFilterSurveyJson(this.surveyJson, this.activeNodeName), true);
      this.$message.success('保存成功');
    },
    // 提交问卷的操作
    handleOnSubmit() {
      if (!this.qsQuestionId) return;
      // 校验问卷是否填写完成
      if (
        this.status === QUESTIONNAIRE_STATUS.TO_BE_FILLED &&
        !validateQuestion(this.questionObject, this.qsInformation.answer, this.isInitiator, this)
      ) {
        this.$message.error('请完善问卷必填项');
        return;
      }
      // 校验风险是否存在不确定风险
      if (
        this.status === QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED &&
        !validateRiskLevel(this.qsInformation.qsRsTemplateList)
      ) {
        this.$message.error('当前存在不确定风险，不可提交');
        return;
      }
      // 状态待填写时的处理函数
      let status = null;
      if (this.status === QUESTIONNAIRE_STATUS.TO_BE_FILLED) {
        status = QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED;
      }
      if (this.status === QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED) {
        status = QUESTIONNAIRE_STATUS.COMPLETED;
        // 为答案对象添加key值
        Object.keys(this.questionObject).forEach((key) => {
          if (this.qsInformation.answer[key] === undefined) this.qsInformation.answer[key] = '';
        });
      }
      if (!status) return;
      requestSaveQsList({ ...this.qsInformation, status }).then((res) => {
        if (!res || res.isError) return;

        this.$message.success('提交成功');
        this.$router.replace({ path: '/risk-assessment/management' });
      });
    },
    // 选择答案的处理逻辑
    handleCheckboxChange(checkArr, e) {
      const allCheckArr = this.questionObject[this.questionName].choices.map((i) => i.value);

      if (e.current === 'all') {
        if (checkArr.includes('all')) {
          this.formData.value = [...allCheckArr, 'all'];
        } else {
          this.formData.value = [];
        }
      } else if (e.current === 'none') {
        if (checkArr.includes('none')) {
          this.formData.value = ['none'];
        }
      } else if (e === 'isCheckAll') {
        if (
          !checkArr.includes('all') &&
          this.formData.value.sort().toString().includes(allCheckArr.sort().toString())
        ) {
          this.formData.value.push('all');
        }
      } else {
        const contains = e.current !== 'other' && checkArr.includes('all') ? ['none', 'all'] : ['none'];
        this.formData.value = this.formData.value.filter((i) => !contains.includes(i));
        if (
          !checkArr.includes('all') &&
          this.formData.value.sort().toString().includes(allCheckArr.sort().toString())
        ) {
          this.formData.value.push('all');
        }
      }

      this.formData.value.sort();
    },
    // dialog关闭时重置表单
    handleOnDialogClose() {
      this.formData = {
        type: [],
        label: [],
      };
      this.files = [];
    },
    // 单个文件上传成功的操作
    oneFileSuccess({ file, response }) {
      requestAddQsDetail({
        content: response.data,
        qsQuestionId: this.qsQuestionId,
        questionName: this.questionName,
        type: this.actionType,
      }).then((res) => {
        if (!res || res.isError) return;
        file.id = res.data;
        this.$message.success('保存成功');

        const textEl = document.querySelector(`.survey #${this.questionId} .text-${ANSWER_ACTIONS.UPLOAD}`);
        textEl.innerHTML = this.files.filter((i) => i.status === 'success').length;
      });
    },
    // 单个文件删除的操作
    oneFileRemove(id) {
      const res = requestDeleteQsDetail(id);
      if (!res || res.isError) return;
      this.$message.success('删除文件成功');

      const textEl = document.querySelector(`.survey #${this.questionId} .text-${ANSWER_ACTIONS.UPLOAD}`);
      const fileNum = this.files.filter((i) => i.status === 'success').length;
      textEl.innerHTML = fileNum > 0 ? fileNum : '';
    },
    // 当问题隐藏状态更改时的操作
    onVisibleChanged(name, visible) {
      this.$set(this.questionObject[name], 'unVisible', !visible);
    },
    // 当更改页数的操作
    onChangePageNo(e) {
      const pageNo = e.node.getParent() ? e.node.getParent().getIndex() : e.node.getIndex();
      this.$refs.survey.changePageNoForcing(pageNo);
      this.$nextTick(() => {
        const surveyEl = document.querySelector('.survey-content');
        const questionEl = surveyEl.querySelector(`.sd-question[data-name='${e.node.value}']`);
        setTimeout(() => {
          surveyEl.scrollTo({
            top: questionEl?.offsetTop ?? 0,
            behavior: 'smooth',
          });
        }, 1);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.risk-assessment-management-start {
  .start-filling {
    .empty-question {
      height: calc(100vh - 265px);
      display: flex;
      justify-content: center;
      align-items: center;
      color: var(--td-font-gray-4);
    }
    /deep/ .t-tree {
      .t-tree__empty {
        display: none;
      }
      .t-is-active .t-tree__label {
        background-color: #fff;
      }
      .t-tree__label {
        flex: 1;
        overflow-x: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;

        .tree-node {
          &.is-active {
            color: #54b780;
          }
        }
      }
    }
  }
  .risk-form {
    padding: 20px 0;
    overflow-x: hidden;
    .risk-discovery {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-weight: 600;
      }
      .risk-box {
        display: flex;
        padding: 2px;
        background: #f3f3f3;
        border-radius: 3px;
        // align-items: center;
        .risk-box__item {
          width: 86px;
          height: 28px;
          border-radius: 2px;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          color: rgba(0, 0, 0, 0.6);
          &.red {
            background: #f36d78;
            color: rgba(255, 255, 255, 0.9);
          }
          &.green {
            background: #48c79c;
            color: rgba(255, 255, 255, 0.9);
          }
          &.blue {
            background: #0052d9;
            color: rgba(255, 255, 255, 0.9);
          }
        }
      }
    }
    /deep/ .t-form__label {
      // line-height: inherit;
      // white-space: wrap;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    /deep/ .t-space-item {
      border: 1px solid #e7e7e7;
      border-radius: 6px;
      padding: 16px 16px 24px;
    }
    /deep/ .t-radio-group {
      background-color: rgba(0, 0, 0, 0);
      gap: 16px;
      .t-radio__label {
        display: inline;
        white-space: inherit;
      }
      &.level {
        gap: 0;
        width: 100%;
        padding: 4px;
        background: #f8f8f8;
        box-shadow: inset 0px 1px 2px rgba(0, 0, 0, 0.1);
        border-radius: 100px;
        .t-radio-group__bg-block {
          display: none;
        }
        .t-radio-button {
          width: 25%;
          height: 32px;
          display: flex;
          justify-content: center;
          &:first-child {
            border-radius: 40px 0px 0px 40px;
          }
          &:nth-child(4) {
            border-radius: 0px 40px 40px 0px;
          }
          // opacity: 0.5;
          // &.t-is-checked {
          //   opacity: 1;
          // }
          .t-radio-button__label {
            color: #fff;
          }
        }
      }
    }
    /deep/ .t-checkbox-group {
      .t-checkbox__label {
        display: inline;
        white-space: inherit;
        width: fit-content;
      }
    }
  }
  /deep/ .t-comment__detail {
    white-space: pre-line;
  }
  /deep/ .t-form__controls-content {
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
  }
}
</style>
